<template>
  <a-form :model="ruleForm"
          ref="ruleForm"
          v-bind="layout"
          :rules="rules"
          @finish="handleFinish">
    <a-form-item label="实验方案名称" name="experiment_program_name">
      <a-input v-model:value="ruleForm.experiment_program_name"/>
    </a-form-item>
    <a-form-item label="实验名称" name="experiment_name">
      <a-select
          v-model:value="ruleForm.experiment_name"
          style="width: 120px"
          ref="select"
      >
        <a-select-option
            v-for="item in experimentNameSelectionOptions"
            :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="实验目的" name="purpose">
      <a-input v-model:value="ruleForm.purpose"/>
    </a-form-item>
    <a-form-item label="实验原理" name="experimental_principle">
      <a-input v-model:value="ruleForm.experimental_principle"/>
    </a-form-item>
    <a-form-item label="附件" name="annex">
      <a-upload
          :fileList="ruleForm.annexFileList"
          :beforeUpload="beforeannexUpload"
          :headers="headers"
          @change="handleannexChange"
      >
        <a-button>
          <upload-outlined/>
          选择
        </a-button>
      </a-upload>
    </a-form-item>
    <a-form-item label="原料名称" name="raw_material_name">
      <a-input v-model:value="ruleForm.raw_material_name"/>
    </a-form-item>
    <a-form-item label="纯度" name="purity">
      <a-input v-model:value="ruleForm.purity"/>
    </a-form-item>
    <a-form-item label="原料来源" name="raw_material_source">
      <a-input v-model:value="ruleForm.raw_material_source"/>
    </a-form-item>
    <a-form-item label="设备名称" name="equipment_name">
      <a-input v-model:value="ruleForm.equipment_name"/>
    </a-form-item>
    <a-form-item label="设备厂家" name="equipment_manufacturer">
      <a-input v-model:value="ruleForm.equipment_manufacturer"/>
    </a-form-item>
    <a-form-item label="设备型号" name="device_model">
      <a-input v-model:value="ruleForm.device_model"/>
    </a-form-item>
    <a-form-item label="数量" name="quantity">
      <a-input v-model:value="ruleForm.quantity"/>
    </a-form-item>
    <a-form-item label="实验步骤" name="equipment_steps">
      <a-input v-model:value="ruleForm.equipment_steps"/>
    </a-form-item>
    <!--    <a-form-item label="审核状态" name="approval_status">-->
    <!--      <a-input v-model:value="ruleForm.approval_status" />-->
    <!--    </a-form-item>-->
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import {message} from 'ant-design-vue'
import {UploadOutlined} from '@ant-design/icons-vue'

export default {
  name: 'AddOrEditExperimentDesign',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  components: {
    UploadOutlined,
  },
  data() {
    let validateExperimentName = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择实验名称");
      }
    };
    let validateExperimentProgramName = async (rule, value) => {
      // console.log('gsdadas', value)
      if (value === "") {
        return Promise.reject("请填写实验方案名称");
      }
    };
    return {
      ruleForm: {
        experiment_name: '',
        experiment_program_name: '',
        purpose: '',
        experimental_principle: '',
        annexFileList: [],
        raw_material_name: '',
        purity: '',
        raw_material_source: '',
        equipment_name: '',
        equipment_manufacturer: '',
        device_model: '',
        quantity: '',
        equipment_steps: '',
        // approval_status: '',
      },
      rules: {
        experiment_program_name: [
          {
            validator: validateExperimentProgramName,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        experiment_name: [
          {
            validator: validateExperimentName,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
      },
      layout: {
        labelCol: {span: 6},
        wrapperCol: {span: 14},
      },
      submitting: false,
      experimentNameSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      this.experimentNameSelectionOptions = []
      this.axios
          .get('/experiment_management/get_passed_experiment/')
          .then((res) => {
            const data = res.data
            for (let i = 0; i < data.length; ++i) {
              this.experimentNameSelectionOptions.push({
                url:
                    'http://127.0.0.1:8000/api/experiment_management/experiment_information/' +
                    data[i].experiment_id +
                    '/',
                label: data[i].experiment_name,
              })
            }
            this.ruleForm.experiment_name = data.length === 0 ? '' : data[0].url
            if (this.url !== '') {
              this.axios
                  .get(this.url)
                  .then((res) => {
                    const data = res.data
                    this.ruleForm.experiment_program_name =
                        data.experiment_program_name
                    this.ruleForm.experiment_name = data.experiment_name
                    this.ruleForm.purpose = data.purpose
                    this.ruleForm.experimental_principle =
                        data.experimental_principle
                    this.ruleForm.raw_material_name = data.raw_material_name
                    this.ruleForm.purity = data.purity
                    this.ruleForm.raw_material_source = data.raw_material_source
                    this.ruleForm.equipment_name = data.equipment_name
                    this.ruleForm.equipment_manufacturer =
                        data.equipment_manufacturer
                    this.ruleForm.device_model = data.device_model
                    this.ruleForm.quantity = data.quantity
                    this.ruleForm.equipment_steps = data.equipment_steps
                    // this.ruleForm.approval_status = data.approval_status
                    // 若有附件，则装入列表
                    if (data.annex_filename !== '') {
                      // console.log('not null')
                      this.ruleForm.annexFileList.push({
                        uid: '-1',
                        name: data.annex_filename,
                      })
                    }
                  })
                  .catch((error) => {
                    console.log('Error', error.message)
                  })
            }
          })
          .catch((error) => {
            console.log('Error', error.message)
            this.ruleForm.experiment_name = ''
          })
    },
    handleFinish(values) {
      this.submitting = true
      const {annexFileList} = this.ruleForm
      const formData = new FormData()
      formData.append('experiment_program_name', values.experiment_program_name)
      formData.append('experiment_name', values.experiment_name)
      formData.append('purpose', values.purpose)
      formData.append('experimental_principle', values.experimental_principle)
      formData.append('raw_material_name', values.raw_material_name)
      formData.append('purity', values.purity)
      formData.append('raw_material_source', values.raw_material_source)
      formData.append('equipment_name', values.equipment_name)
      formData.append('equipment_manufacturer', values.equipment_manufacturer)
      formData.append('device_model', values.device_model)
      formData.append('quantity', values.quantity)
      formData.append('equipment_steps', values.equipment_steps)
      // formData.append('approval_status', values.approval_status)
      annexFileList.forEach((file) => {
        // console.log(file.originFileObj)
        // console.log(file)
        // 若选择了文件，那么会有originFileObj属性，这种情况直接上传就可以，
        // 若无originFileObj属性，则说明是在编辑，且没有更改文件，文件列表中只有文件名而无文件实体，
        // 这个时候不传文件参数，让后端保持原文件不变
        if ('originFileObj' in file) {
          formData.append('annex', file.originFileObj)
        }
      })
      if (this.url !== '') {
        // 若文件列表为空，则附加属性通知后端
        if (this.ruleForm.annexFileList.length === 0) {
          formData.append('annex_empty', true)
        }
        if (this.ruleForm.annexFileList.length === 0) {
          formData.append('annex_empty', true)
        }
        if (this.ruleForm.annexFileList.length === 0) {
          formData.append('annex_empty', true)
        }
        this.axios
            .put(this.url, formData)
            .then(() => {
              this.submitting = false
              message.success('修改成功！')
              this.$emit('operate-success')
            })
            .catch((error) => {
              this.submitting = false
              message.error('修改失败！')
              this.$emit('operate-failed')
              console.log('Error', error.message)
            })
      } else {
        this.axios
            .post('/experiment_management/experiment_design/', formData)
            .then(() => {
              this.submitting = false
              message.success('添加成功！')
              this.$emit('operate-success')
            })
            .catch((error) => {
              this.submitting = false
              message.error('添加失败！')
              this.$emit('operate-failed')
              console.log('Error', error.message)
            })
      }
    },
    beforeannexUpload(file) {
      this.ruleForm.annexFileList = [...this.ruleForm.annexFileList, file]
      return false
    },
    handleannexChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      // console.log('before:', fileList)
      fileList = fileList.slice(-1)
      // console.log('after:', fileList)
      this.ruleForm.annexFileList = fileList
    },
  },
}
</script>
